package com.zhu.storesmanager;


import java.util.ArrayList;

import com.zhu.storesmanager.common.MyLocation;
import com.zhu.storesmanager.common.MyLocation.LocationResult;
import com.zhu.storesmanager.models.VisitTaskInfo;
import com.zhu.storesmanager.network.PutSupervisorVisitData;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.views.ObservableScrollView;
import com.zhu.storesmanager.views.PopCheckView;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 督导门店拜访页面
 */
public class SvVisitTaskActivity extends Activity implements View.OnClickListener{

	 private final static int PUT_DIALOG = 0; //上传dialog
	//开始拜访和结束拜访门店ID
	public static final String STARTCHECKID = "00000000"; //开始拜访门店ID
    public static final String STOPCHECKID = "99999999"; //结束拜访门店ID
    //签入或者签出
    public static final int CHECK_IN = 0;
	public static final int CHECK_OUT = 1;

	//异步查询数据库token
    private final static int TASK_LIST_QUERY_TOKEN = 0; //查询所有拜访任务 token
    private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler

    //界面
    private ObservableScrollView mScrollView;
    private LinearLayout mBodyLayout = null;
    private TextView mVisitTaskinfoTextView = null;
    private TextView mScollClew = null;
    private TextView mNoneTextView = null;
    private FrameLayout mFrameLayout = null;
    private Button mStartVisitButton = null;
    private Button mEndVisitButton = null;
    private int mVisitedCount = 0; //已拜访门店数量
    private boolean isStartVisited = false; //是否已经开始拜访
    private boolean isEndVisited = false; //是否已经完成拜访
    private ArrayList<VisitTaskInfo> mVisitTaskList = new ArrayList<VisitTaskInfo>(); //拜访门店集合
    private VisitTaskInfo mCheckingVisitTaskInfo = null; //正在拜访的门店信息
    private View mCheckingView = null;
    private MyLocation mMyLocation = null; //定位
    private Location mCurLocation = null; //当前定位结果
    private PopCheckView mPopCheckView = null; //CHECK 弹窗
    private int mCurCheckType = -1; //当前签入OR签出
    private PutSupervisorVisitData mPutSupervisorVisitData = null; //上传单条任务数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sv_visittask);
        setupViews();
        initData();
    }

    /**
     * 初始化界面
     */
    private void setupViews(){
    	 mScrollView = (ObservableScrollView) findViewById(R.id.svvisittask_scrollview);
         mScrollView.setScrollViewListener(mScrollViewListener);
         mNoneTextView = (TextView) findViewById(R.id.none_text);
         mNoneTextView.setVisibility(View.VISIBLE);
         
         mScollClew = (TextView) findViewById(R.id.visitTask_scrollclew);
         mBodyLayout = (LinearLayout) findViewById(R.id.svvisittask_view_bodyview);
         mVisitTaskinfoTextView = (TextView) findViewById(R.id.svvisittask_textinfo);
         mFrameLayout = (FrameLayout)findViewById(R.id.content_layout); 

         mStartVisitButton = (Button)findViewById(R.id.svvisittask_startvisit);
         mEndVisitButton = (Button)findViewById(R.id.svvisittask_endtvisit);
         mStartVisitButton.setOnClickListener(this);
         mEndVisitButton.setOnClickListener(this);

         findViewById(R.id.svvisittask_bottom_back).setOnClickListener(this);
         ((TextView)findViewById(R.id.title_text)).setText(R.string.visittask_title);
         mPopCheckView = new PopCheckView(this, mFrameLayout);
    }

    /**
     * 初始化数据
     */
    private void initData(){
    	if(mDataQueryHandler == null){
    		mDataQueryHandler = new DataQueryHandler(this.getContentResolver());	
    	}
    	startTaskListAsyncQuery();
    }

    /**
     * 获取清单拜访列表
     */
    private void startTaskListAsyncQuery() {
        try {
        	mDataQueryHandler.startQuery(TASK_LIST_QUERY_TOKEN, null,
                    StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI,
                    null, null, null, null/*StoresManagerSettings.SupervisorVisitTaskColumns.ITEMNO + " ASC"*/);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新清单拜访数据
     * @param cursor 数据库数据
     */
    private void updateList(Cursor cursor) {
        mVisitTaskList.clear();
        mVisitedCount = 0;

        String where = "";
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns._ID);
            final int visitId = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.VISITID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.STOREID);
            final int checkintimeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKIN_TIME);
            final int checkouttimeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKOUT_TIME);
            final int visitedIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.VISITED_STATUS);
            final int storeNameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.STORENAME);

            while (cursor.moveToNext()) {
            	String storeid = cursor.getString(storeidIndex);
            	long checkintime = cursor.getLong(checkintimeIndex);
            	if(storeid.equals(STARTCHECKID)){
            		if(checkintime > 1){
            			isStartVisited = true;
            		}
            	}else if(storeid.equals(STOPCHECKID)){
            		if(checkintime > 1){
            			isEndVisited = true;
            		}
            	}else{
            		VisitTaskInfo visitTaskInfo = new VisitTaskInfo();
                	visitTaskInfo.mDbId = cursor.getLong(idIndex);
                	visitTaskInfo.mStoreId = storeid;
                	visitTaskInfo.mVisitId = cursor.getString(visitId);
                	visitTaskInfo.mName = cursor.getString(storeNameIndex);
                	visitTaskInfo.mCheckinTime = checkintime;
                	visitTaskInfo.mCheckoutTime = cursor.getLong(checkouttimeIndex);
                	visitTaskInfo.isVisited = cursor.getInt(visitedIndex) == 1 ? true : false;
                	if(visitTaskInfo.isVisited){
                        mVisitedCount++;
                    }
                	mVisitTaskList.add(visitTaskInfo);
                    if(where.length() == 0){
                    	where = "cid = \"" + visitTaskInfo.mStoreId +"\"";
                    }else{
                    	where += " OR cid = \"" + visitTaskInfo.mStoreId +"\"";
                    }
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("updateList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        	}
        }

//        try {
//        	mDataQueryHandler.startQuery(CNAME_LIST_QUERY_TOKEN, null,
//                    SalesSettings.CustomerSColumns.CONTENT_URI,
//                    null, where, null, null);
//        } catch (SQLiteException e) {
//            e.printStackTrace();
//        }
//
        updateInfoTextview(mVisitTaskList.size(), mVisitedCount);
        updateVisitButton();
        updateView();
    }

    /**
     * 更新拜访提示界面
     * @param needVisitCount 需要拜访的总数
     * @param visitedCount 已拜访门店数量
     */
    private void updateInfoTextview(int needVisitCount, int visitedCount) {
//      String info = getResources().getString(R.string.needvisitTask) + "<font color=#FF3030>"
//              + needVisitCount + "</font>" + getResources().getString(R.string.visitedCount)
//              + getResources().getString(R.string.douhao)
//              + getResources().getString(R.string.visitedTask) + "<font color=#FF3030>"
//              + visitedCount + "</font>" + getResources().getString(R.string.visitedCount);
    	String text = getResources().getString(R.string.visitclew, needVisitCount, (needVisitCount - visitedCount));
    	mVisitTaskinfoTextView.setText(text/*Html.fromHtml(info)*/);
     }

    /**
     * 更新拜访button状态
     */
    private void updateVisitButton(){
    	if(isStartVisited){ //已经开始拜访
    		mStartVisitButton.setEnabled(false);
    		mStartVisitButton.setBackgroundResource(R.drawable.login_button_disable);
    		if(isEndVisited){ //已经结束拜访
    			mEndVisitButton.setEnabled(false);
        		mEndVisitButton.setBackgroundResource(R.drawable.login_button_disable);
    		}else{
    			mEndVisitButton.setEnabled(true);
        		mEndVisitButton.setBackgroundResource(R.drawable.login_button_red);
    		}
    	}else{
    		if(mVisitTaskList.size() > 0){//拜访门店数量大于0
    			mStartVisitButton.setEnabled(true);
        		mStartVisitButton.setBackgroundResource(R.drawable.login_button_red);
    		}else{
    			mStartVisitButton.setEnabled(false);
        		mStartVisitButton.setBackgroundResource(R.drawable.login_button_disable);
    		}
    		mEndVisitButton.setEnabled(false);
    		mEndVisitButton.setBackgroundResource(R.drawable.login_button_disable);
    	}
    }

    /**
     * 更新列表界面
     */
    private void updateView(){
    	mBodyLayout.removeAllViews();
		for (int i = 0; i < mVisitTaskList.size(); i++) {
			VisitTaskInfo visitTaskInfo = mVisitTaskList.get(i);
			View view = getVisitTaskItem(visitTaskInfo);
            mBodyLayout.addView(view);
		}
		//判断隐藏空文本提示
		if(mBodyLayout.getChildCount() > 0){
			mNoneTextView.setVisibility(View.GONE);
		}else{
			mNoneTextView.setVisibility(View.VISIBLE);
		}

		//是否显示可以滚动提示
//		mScrollView.post(new Runnable() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				if (mScrollView.canScrollView()) {
//					mScollClew.setVisibility(View.VISIBLE);
//				}
//			}
//		});
	}

    /**
     * 获取列表项界面
     */
    private View getVisitTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.visittasklist_item, null);
        View content = row.findViewById(R.id.visittas_rowcontent);
        content.setTag(info);
        ImageView task = (ImageView) row.findViewById(R.id.visittast_item_status);
        if(info.isVisited){ //已经拜访完成则显示勾图片
            task.setImageResource(R.drawable.ok);
        }else{
            content.setOnClickListener(this);
        }
        TextView name = (TextView) row.findViewById(R.id.visittast_item_name);
        name.setText(info.mName);
        return row;
    }

    /**
     * 异步数据查询
     */
    private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case TASK_LIST_QUERY_TOKEN:
                	updateList(cursor);
                    break;
                default:
                    Log.e("onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }
    }

    /**
     * 是否可以开始拜访
     * @return true 可以开始拜访门店
     */
    private boolean canVisit(){
    	if(isStartVisited){
    		return true;
    	}else{
    		Actions.toastShort(this, this.getString(R.string.startvisitfirst));
    		return false;
    	}
    }

    /**
     * 点击事件监听
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.svvisittask_bottom_back: //返回
					this.finish();
					break;
				case R.id.visittas_rowcontent: //列表门店查访
					if(canVisit()){
                		popCheckView((VisitTaskInfo) arg0.getTag(), arg0);
                	}
					break;
				case R.id.svvisittask_startvisit: //开始拜访任务
					startVisit(STARTCHECKID);
					break;
				case R.id.svvisittask_endtvisit: //结束拜访任务
					popEndVisitDialog();
					break;
			}
		}
	}

	/**
     * 弹出门店拜访选择框
     * @param visitTaskInfo 门店信息
     * @param view 列表项View
     */
    private void popCheckView(VisitTaskInfo visitTaskInfo, View view) {
    	if(visitTaskInfo.isVisited){
    		return;
    	}
    	mCheckingView = view;
    	mCheckingVisitTaskInfo = visitTaskInfo;
    	mPopCheckView.showPopTextView(visitTaskInfo);
    }

    /**
     * 开始拜访
     */
    private void startVisit(String storeid){
//        if(!Actions.isOpenedGpsAndNetwork(this, true)){ //检查GPS和网络
//            return;
//        }
//        VisitTaskInfo item = new VisitTaskInfo();
//    	item.mStoreId = storeid;
//    	mCheckingVisitTaskInfo = item;
//    	if(mMyLocation == null){
//    		mMyLocation = new MyLocation(this, true, false);
//    	}
//    	mMyLocation.getLocation(mLocationResult, true);
    	VisitTaskInfo info = new VisitTaskInfo();
    	info.mStoreId = storeid;
    	info.mCheckinTime = System.currentTimeMillis();
         boolean success = DataUtils.saveStoresCheckinInfo(this, info, 0, 0, false);
         if(success){ //是否保存成功
        	 if(info.mStoreId.equals(STARTCHECKID)){
        		 isStartVisited = true;
        		 updateVisitButton();
        	 }else if(info.mStoreId.equals(STOPCHECKID)){
        		 isEndVisited = true;
        		 updateVisitButton();
        	 }
         }
    }

    /**
     * 定位结果
     */
    public LocationResult mLocationResult = new LocationResult() {
        public void onLocationResult(final Location location) {
            // Got the location!
            if (location != null) {
                mCurLocation = location;
            }
            if(mCheckingVisitTaskInfo != null && 
            		(mCheckingVisitTaskInfo.mStoreId.equals(STARTCHECKID) 
            				|| mCheckingVisitTaskInfo.mStoreId.equals(STOPCHECKID))){ //开始或者结束拜访
            	stopVitit();
            }else{ //结束签入or签出
                stopCheck();
            }
        }
    };

    /**
     * 结束拜访
     */
    private void stopVitit(){
    	 double lat = 0;
         double lng = 0;
         if(mCurLocation != null){//获取经纬度
             lat = mCurLocation.getLatitude();
             lng = mCurLocation.getLongitude();
         }
         mCheckingVisitTaskInfo.mCheckinTime = mMyLocation.getCurrentTime(); //获取拜访时间
         boolean success = DataUtils.saveStoresCheckinInfo(this, mCheckingVisitTaskInfo, lat, lng, mMyLocation.isNetworkTime());
         if(success){ //是否保存成功
        	 Actions.toastShort(this, getString(R.string.visitsuccess));
        	 if(mCheckingVisitTaskInfo.mStoreId.equals(STARTCHECKID)){
        		 isStartVisited = true;
        		 updateVisitButton();
        	 }else if(mCheckingVisitTaskInfo.mStoreId.equals(STOPCHECKID)){
        		 isEndVisited = true;
        		 updateVisitButton();
        	 }
         }else{
        	 mCheckingVisitTaskInfo.mCheckinTime = 0;
         }
         mCheckingVisitTaskInfo = null;
    }

    /**
     * 签入签出
     * @param type 类型 签入OR签出
     * @param true 开始签入签出
     */
    public boolean startCheck(int type){
    	if(type == CHECK_OUT){
    		if(!DatabaseUtil.canEndVisit(this, Integer.parseInt(mCheckingVisitTaskInfo.mVisitId), mCheckingVisitTaskInfo.mStoreId)){
    			Actions.toastShort(this, getString(R.string.checkout_error));
    			gotoInputActivity();
    			return false;
    		}
    	}
        if(!Actions.isOpenedGpsAndNetwork(this, true)){
            return false;
        }
        mCurLocation = null;
    	mCurCheckType = type;
    	if(mMyLocation == null){
    		mMyLocation = new MyLocation(this, true, false);
    	}
    	mMyLocation.getLocation(mLocationResult, true);
    	return true;
    }

    /**
     * 签出OR签入结束
     */
    private void stopCheck(){
        boolean success = saveData();
        if(mCheckingVisitTaskInfo.isVisited){
            mVisitedCount++;
            updateInfoTextview(mVisitTaskList.size(), mVisitedCount);
            ImageView task = (ImageView) mCheckingView.findViewById(R.id.visittast_item_status); //更新OK状态
            task.setImageResource(R.drawable.ok);
            if(mVisitTaskList.size() == mVisitedCount){ //自动结束拜访
            	startVisit(STOPCHECKID);
            }
            startPutData(Integer.parseInt(mCheckingVisitTaskInfo.mVisitId));
        }
        mCheckingVisitTaskInfo = null;
    }
 
    /**
     * 保存签入OR签出数据
     */
    private boolean saveData(){
        double lat = 0;
        double lng = 0;
        if(mCurLocation != null){ //获取经纬度
            lat = mCurLocation.getLatitude();
            lng = mCurLocation.getLongitude();
        }
        if(mCurCheckType == CHECK_IN){//签入
            mCheckingVisitTaskInfo.mCheckinTime = mMyLocation.getCurrentTime(); //获取签入时间
            boolean success = DataUtils.saveStoresCheckinInfo(this, mCheckingVisitTaskInfo, lat, lng, mMyLocation.isNetworkTime());
            if(success){
                if(lat == 0 && lng == 0){ //GPS值为空
                    Actions.toastShort(this, getString(R.string.checkinsuccess_fail));
                }else{
                    Actions.toastShort(this, getString(R.string.checkin_success));
                }
                return true;
            }else{//数据保存失败
                mCheckingVisitTaskInfo.mCheckinTime = 0;
                return false;
            }
        }else{ //签出
            mCheckingVisitTaskInfo.mCheckoutTime = mMyLocation.getCurrentTime(); //获取签入时间
            boolean success = DataUtils.saveStoresCheckoutInfo(this, mCheckingVisitTaskInfo, lat, lng, mMyLocation.isNetworkTime());
            if(success){
                if(lat == 0 && lng == 0){ //GPS值为空
                    Actions.toastShort(this, getString(R.string.checkoutsuccess_fail));
                }else{
                    Actions.toastShort(this, getString(R.string.checkout_success));
                }
                mCheckingVisitTaskInfo.isVisited = true;
                return true;
            }else{ //数据保存失败
                mCheckingVisitTaskInfo.mCheckoutTime = 0;
                return false;
            }
        }
    }

    /**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 返回事件处理
     */
    private boolean doBack(){
        if(mPopCheckView != null){
            return mPopCheckView.doBack();
        }
        return false;
    }

    /**
     * 跳转门店拜访内容界面
     * @param info 门店信息
     */
    public void gotoVisitContentActivity(VisitTaskInfo info) {
        Intent intent = new Intent(this, SvStoreSampleActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", info);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 弹出结束拜访对话框
     */
    private void popEndVisitDialog(){
        Actions.alertShowDetails(this, getString(R.string.endvisitclew),
                getString(R.string.endvisitcontent),
                R.string.button_ok, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        startVisit(STOPCHECKID);
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

	/**
	 * 滑动监听
	 */
	private ObservableScrollView.ScrollViewListener mScrollViewListener = new ObservableScrollView.ScrollViewListener(){

        @Override
        public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx,
                int oldy) {
            // TODO Auto-generated method stub
            if(Actions.DEBUG){
                Log.e("onScrollChanged="+ Math.abs(y - oldy));
            }
            if(Math.abs(y - oldy) > 1){
                mScollClew.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 开始上传数据
     */
    private void startPutData(int visitId){
    	if(DataUtils.mUserData.isOffline){ //离线登录不能上传数据
    		return;
    	}
    	showDialog(PUT_DIALOG);
    	if(mPutSupervisorVisitData == null){
    		mPutSupervisorVisitData = new PutSupervisorVisitData(this, mHandler);
    	}
    	mPutSupervisorVisitData.startSync(visitId);
    }

    /**
     * 上传结果消息处理
     */
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
            switch (msg.what) {
            	case PutSupervisorVisitData.SYNC_FAILEDEND:
            		dismissDialog(PUT_DIALOG);
            		Actions.toastShort(SvVisitTaskActivity.this, R.string.put_fail);
            		break;
            	case PutSupervisorVisitData.SYNC_SUCCESSEND:
            		dismissDialog(PUT_DIALOG);
            		Actions.toastShort(SvVisitTaskActivity.this, R.string.put_success);
            		break;
            }
    	}
    };

    /**
     * 上传进度提示
     */
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case PUT_DIALOG:
                ProgressDialog pd = new ProgressDialog(this);
                pd.setMessage(this.getString(R.string.putdataing)
                        + getString(R.string.please_wait));
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
                return pd;

            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    /**
     * 跳转没有填写数据的界面
     */
    private void gotoInputActivity(){
    	Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putParcelable("info", mCheckingVisitTaskInfo);
		intent.putExtras(bundle);
    	if(DatabaseUtil.VISIT_STATUS[0] == 0){
    		intent.setClass(this, SvStoreSampleActivity.class);
			startActivity(intent);
    	}else if(DatabaseUtil.VISIT_STATUS[1] == 0){
    		intent.setClass(this, SvStoreBoothActivity.class);
			startActivity(intent);
    	}else if(DatabaseUtil.VISIT_STATUS[2] == 0){
    		intent.setClass(this, SvStoreSalesActivity.class);
			startActivity(intent);
    	}else if(DatabaseUtil.VISIT_STATUS[3] == 0){
    		intent.setClass(this, SvStorePOSMActivity.class);
			startActivity(intent);
    	}else if(DatabaseUtil.VISIT_STATUS[4] == 0){
    		intent.setClass(this, SvStoreCompeteActivity.class);
			startActivity(intent);
    	}else if(DatabaseUtil.VISIT_STATUS[5] == 0){
    		intent.setClass(this, SvStorePromoterInfoActivity.class);
			startActivity(intent);
    	}else if(DatabaseUtil.VISIT_STATUS[6] == 0){
    		intent.setClass(this, SpecialTaskActivity.class);
			startActivity(intent);
    	}
    }
}
